/*
 * Copyright 2012 Alan Burlison, alan@bleaklow.com.  All rights reserved.
 * Use is subject to license terms.  See LICENSE.txt for details.
 */

/*
 * Simple task classes.
 */

#ifndef Task_h
#define Task_h

#include <stdint.h>

// Maximum time into the future - approximately 50 days.
#define MAX_TIME UINT32_MAX

/*
 * A simple task.
 */
class Task {
public:
    /*
     * Can the task run?  if so, run it and return true, otherwise return false.
     * now - current time, in milliseconds.
     */
    virtual bool run(uint32_t now) = 0;
};

/*
 * A task that is triggered by an external event.
 */
class TriggeredTask : public Task {
public:
    /*
     * Trigger the task.
     */
    inline void trigger() { triggered = true; }

    /*
     * Reset the trigger.
     */
    inline void resetTrigger() { triggered = false; }

    /*
     * Check if the task is runnable.
     */
    inline bool isTriggered() { return triggered; }

protected:
    bool triggered;   // True if the task has been triggered.
};

/*
 * A task that is run on a periodic basis.
 */
class TimedTask : public Task {
public:
    /*
     * Create a periodically executed task.
     * when - the system clock tick when the task should run, in milliseconds.
     */
    inline TimedTask(uint32_t when) { runTime = when; }

    /*
     * Set the system clock tick when the task can next run.
     * when - the system clock tick when the task should run, in milliseconds.
     */
    inline void setRunTime(uint32_t when) { runTime = when; }

    /*
     * Increment the system clock tick when the task can next run.
     * inc - system clock increment, in milliseconds.
     */
    inline void incRunTime(uint32_t inc) { runTime += inc; }

    /*
     * Get the system clock tick when the task can next run.
     * return - system clock tick when the task is next due to run.
     */
    inline uint32_t getRunTime() { return runTime; }

    /*
     * Check if the task can run now.
     */
    inline bool canRunNow(uint32_t now) { return now >= runTime; }
protected:
    uint32_t runTime;   // The  system clock tick when the task can next run.
};

#endif
